<template>
  <a-spin :spinning="loading">
    <div style="display: flex;align-items: center;">
      <span style="font-size: 18px;font-weight: bold">共{{count}}个包裹</span>
      <a-button @click="openProductSkuService" style="margin-left: 10px" type="primary">平台SKU特殊服务列表</a-button>
    </div>
    <common-table
        class="table-container"
        :columns="columns"
        :dataSource="dataList"
        :scroll="{ x: 'max-content' }"
        :slots="['expandedRowRender','pkgStatus', 'saleOrderItem','skus', 'logisticsItem', 'trackItem','action']"
        :rowKey="(record)=>record.saleOrderItem.saleOrderCode"
        @expand="handleExpandedRowsChange"
    >
      <template #expandedRowRender="{ record }">
        <expand-logistics :ref="`expandLogistics-${record.saleOrderItem.saleOrderCode}`" :saleOrderCode="record.saleOrderItem.saleOrderCode" />
      </template>
      <template #pkgStatus="{ record }">
        <logistics-icon :record="record" />
      </template>
      <template #saleOrderItem="{ record }">
        <a-descriptions :column="1">
          <a-descriptions-item label="订单">{{ record.saleOrderItem.saleOrderCode }}</a-descriptions-item>
          <a-descriptions-item label="状态">{{record.saleOrderItem.status + "-" + record.saleOrderItem.statusName}}</a-descriptions-item>
          <a-descriptions-item label="重发单">{{ record.saleOrderItem.reloadFlag }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ record.saleOrderItem.createdDate }}</a-descriptions-item>
          <a-descriptions-item label="重发原因">{{
              (record.saleOrderItem.firstReason ? record.saleOrderItem.firstReason : "") + ">"+
              (record.saleOrderItem.secondReason ? record.saleOrderItem.secondReason : "") + '>' +
              (record.saleOrderItem.thirdReason ? record.saleOrderItem.thirdReason : "") + ">"
            }}</a-descriptions-item>
        </a-descriptions>
      </template>
      <template #skus="{ record }">
        <el-table :data="record.skus" border style="width: 370px"
                  :header-cell-style="()=>{
                    return {
                        backgroundColor: '#ececec',
                        color: '#070707',
                        textAlign: 'center',
                        width: '100%'

                  }}"
                  :cell-style="{'text-align': 'center','color':'black'}">
          <el-table-column v-for="item in innerColumns" :prop="item.dataIndex" :label="item.title" :width="item.width">
            <template #default="scope" v-if="item.dataIndex === 'timeItem'">
              {{ scope.row[item.dataIndex].earliestDeliveryTime + "~" + scope.row[item.dataIndex].latestDeliveryTime }}
            </template>
            <template #default="scope" v-else-if="item.dataIndex === 'otherItem'">
              {{ scope.row[item.dataIndex].poolCode + "-" + scope.row[item.dataIndex].warehouseCode}}
              <br>
              {{scope.row[item.dataIndex].eta }}
            </template>
            <template #default="scope" v-else>{{ scope.row[item.dataIndex] }}</template>
          </el-table-column>
        </el-table>
      </template>
      <template #logisticsItem="{ record }">
        {{record.logisticsItem.deliveryType ? record.logisticsItem.deliveryType : '' + "/" + record.logisticsItem.specialService ? record.logisticsItem.specialService : '' }}
      </template>
      <template #trackItem="{ record }">
        <a-descriptions :column="1">
          <a-descriptions-item label="仓库">{{ record.trackItem.warehouseCode }}</a-descriptions-item>
          <a-descriptions-item label="头程">{{ record.trackItem.containerNo }}</a-descriptions-item>
          <a-descriptions-item label="尾程">
            {{record.trackItem?.shippingMethodNo  + " | " + (record.trackItem?.courierCode == null ? "" : record.trackItem?.courierCode)}}
          </a-descriptions-item>
        </a-descriptions>
      </template>
      <template #action="{ record }">
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" v-if="modulePerm(['order:intercepts'])">
                <span @click="handleMenuClick(record)">订单拦截</span>
              </a-menu-item>
               <a-menu-item key="2" v-if="modulePerm(['order:retransmissions'])">
                 <span @click="openRetransmission(record.saleOrderItem.saleOrderCode)">创建重发单</span>
               </a-menu-item>
              <a-menu-item key="3" v-if="modulePerm(['order:editReason'])">
                <span @click="handleEditReason(record)">修改重发归因</span>
              </a-menu-item>
              <a-menu-item key="4" v-if="modulePerm(['order:operationLog'])">
                <span @click="openLog(record.saleOrderItem.saleOrderCode)">重发单归因操作日志</span>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button type="primary">
            操作
            <DownOutlined />
          </a-button>
        </a-dropdown>
      </template>
    </common-table>
  </a-spin>
  <order-interception-modal ref="orderInterceptionModal" @close="handleClose" :showInterception="showInterception"/>
  <skuService :orderId="orderId" ref="skuServices" :platform="platform" />
  <a-modal v-model:open="visible" title="修改重发归因" @ok="handleOk" @cancel="handleCancel">
    <div>
      <span>重发归因：</span>
      <a-cascader v-model:value="reason" :options="options"
                  :allowClear="false"
                  style="width:auto"
                  :field-names="{ label: 'reason', value: 'reason', children: 'childrenReasonList' }">
      </a-cascader>
    </div>
  </a-modal>
  <a-modal v-model:open="logVisible" title="重发单归因操作日志" width="900px">
    <common-table
        :columns="logColumns"
        :dataSource="logList"/>
  </a-modal>
</template>
<script setup>
import CommonTable from "@/components/commonTable/index.vue";
import {defineProps, ref,nextTick,getCurrentInstance} from "vue";
import ExpandLogistics from "@/views/orderStandardization/components/expandLogistics.vue";
import OrderInterceptionModal from "@/components/modal/orderInterceptionModal.vue";
import LogisticsIcon from "@/views/orderStandardization/components/logisticsIcon.vue";
import {getEditReason, getOperationLog, getReasonTree, getTabLogistics} from "@/api/standard/index.js";
import {modulePerm} from "@utils/modulePerm.js";
import {useRouter} from "vue-router";
import skuService from "@/views/orderStandardization/components/skuService.vue";
import {message} from "ant-design-vue";
const emits = defineEmits(["changeActiveKey"])
const skuServices = ref()
const visible = ref(false)
const logVisible = ref(false)
const props = defineProps({
  orderId:{
    type:String,
    default:''
  },
  platform:{
    type:String,
    default:''
  }
})
const saleOrderCode = ref('')
const options = ref([])
const logColumns = [
  {
    title:"操作",
    dataIndex:"operationLog",
    width:500,
    align:"center",
  },
  {
    title:"操作时间",
    dataIndex:"createTime",
    align:"center",
  },
  {
    title:"操作人",
    dataIndex:"createBy",
    align:"center",
  },
]
const logList = ref([])
const loading = ref(false)
const orderInterceptionModal = ref()
const columns = [
  {
    title:"包裹状态",
    dataIndex:"pkgStatus",
    key: "pkgStatus",
    align:"center",
    width:150,
  },
  {
    title:"易仓订单",
    dataIndex:"saleOrderItem",
    key: "saleOrderItem",
    align:"center",
    width:270,
  },
  {
    title:"SKU",
    dataIndex:"skus",
    key: "skus",
    align:"center",
    width:350,
  },
  {
    title:"物流类型&服务",
    dataIndex:"logisticsItem",
    key: "logisticsItem",
    align:"center",
    width:150,
  },
  {
    title:"延迟发货",
    dataIndex:"delayFor",
    key: "delayFor",
    align:"center",
    width:150,
  },
  {
    title:"轨迹跟踪",
    dataIndex:"trackItem",
    key: "trackItem",
    align:"center",
    width:250,
  },
  {
    title:"操作",
    dataIndex:"action",
    key: "action",
    align:"center",
    width:150,
    fixed:"right",
  }
]
const count = ref(0)
const expandLogistics = ref(null)
const router = useRouter()
const {proxy} = getCurrentInstance()
const showInterception = ref(false)
const dataList = ref([])
const innerColumns = [
  {
    title:"仓库SKU",
    dataIndex:"warehouseSku",
    key: "warehouseSku",
    align:"center",
    width: 150
  },
  {
    title:"数量",
    dataIndex:"qty",
    key: "qty",
    align:"center",
    width:70,
  },
  {
    title:"平台SKU",
    dataIndex:"productSku",
    key: "productSku",
    align:"center",
    width: 150
  },
]
const reason = ref([])
const handleMenuClick = (record) => {
  const { saleOrderCode } = record.saleOrderItem
  orderInterceptionModal.value.init(saleOrderCode)
  showInterception.value = true
}
const handleClose = () => {
  showInterception.value = false
}
const openLog = async (saleOrderCode) => {
  try {
    const res = await getOperationLog({
      saleOrderCode
    })
    logList.value = res.result
    logVisible.value = true
  }catch (e){

  }
}
const handleEditReason = (record) => {
  reason.value[0] = record.saleOrderItem.firstReason ? record.saleOrderItem.firstReason : ""
  reason.value[1] = record.saleOrderItem.secondReason ? record.saleOrderItem.secondReason : ""
  reason.value[2] = record.saleOrderItem.thirdReason ? record.saleOrderItem.thirdReason : ""
  saleOrderCode.value = record.saleOrderItem.saleOrderCode
  visible.value = true
}
const handleOk = async () => {
  try {
    const res = await getEditReason({
      saleOrderCode:saleOrderCode.value,
      orderId:props.orderId,
      firstReason:reason.value[0],
      secondReason:reason.value[1],
      thirdReason:reason.value[2]
    })
    console.log(res)
    message.success('修改成功')
    handleCancel()
    init()
  }catch (e){
   message.error(e)
  }
}
const handleCancel = () => {
  visible.value = false
  reason.value = []
}
const openProductSkuService = () => {
  skuServices.value.init()
}
const openRetransmission = (saleOrderCode) => {
  router.push('/order/retransmission?orderId=' + props.orderId + '&saleOrderCode=' + saleOrderCode)
}

const init = async () => {
  try{
    loading.value = true
    const res = await getTabLogistics({orderId:props.orderId})
    dataList.value = res.result.records
    count.value = res.result.total
    const res1 = await getReasonTree()
    options.value = res1.result
  }catch(e){
    message.error(e)
  } finally{
    loading.value = false
  }
}
/**
 *  监听展开行变化
 */
const handleExpandedRowsChange = (flag,record) => {
  if(flag){
      nextTick(()=>{
        proxy.$refs[`expandLogistics-${record.saleOrderItem.saleOrderCode}`].init()
      })
  }
}
defineExpose({
  init
})
</script>

<style scoped>
:deep(.ant-descriptions-row >td ) {
  padding: 1px;
}
:deep(.el-table) {
  --el-table-row-hover-bg-color: #E4F7FF;
}
</style>
